package wqh.controller.file;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wqh.domain.*;
import wqh.global.GlobalSession;
import wqh.pojo.IPConver;
import wqh.pojo.MapRet;
import wqh.pojo.xkLog;
import wqh.service.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by devts on 2016/11/12.
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/export/monitor")
public class MonitorExport {

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SensorService sensorService;

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private SystemLogService systemLogService;


    @RequestMapping(value = "/getAllMonitor",method = RequestMethod.GET)
    public Object getAllMonitor(HttpServletRequest request, HttpServletResponse response)
    {
        try {
            String sessionID = request.getSession().getId();
            String userName = GlobalSession.getUserNameBySessionID(sessionID);
            if(userName == null) userName = "空用户";

            List<GeoBuilding> geoBuildingList = geoBuildingService.findAllRecord();
            if(geoBuildingList.size() == 0) return MapRet.ERROR("请先录入地理位置信息。");
            List<Device> deviceList = deviceService.findAllRecord();
            if(deviceList.size() == 0) return MapRet.ERROR("请先录入用户信息传输装置信息。");
            List<Sensor> sensorList = sensorService.findAllRecord();
            if(sensorList.size() == 0) return MapRet.ERROR("请先录入传感器类别信息。");
            List<Monitor> monitorList = monitorService.findAllRecord();
            if(monitorList.size() == 0) return MapRet.ERROR("请先录入监测点信息。");
            List<wqh.pojo.MonitorExport> monitorExportList = new ArrayList<wqh.pojo.MonitorExport>();
            for(Monitor monitor : monitorList){
                wqh.pojo.MonitorExport monitorExport = new wqh.pojo.MonitorExport();
                monitorExport.setArea(getGeobuildingName(monitor.getGeo_level_1_id(),geoBuildingList));
                monitorExport.setBuilding(getGeobuildingName(monitor.getGeo_level_2_id(),geoBuildingList));
                monitorExport.setFloor(getGeobuildingName(monitor.getGeo_level_3_id(),geoBuildingList));
                monitorExport.setDevice_name(getDeviceName(monitor.getDevice_id(),deviceList));
                monitorExport.setDevice_ip(getDeviceIP(monitor.getDevice_id(),deviceList));
                monitorExport.setDevice_model(getDeviceModel(monitor.getDevice_id(),deviceList));
                monitorExport.setSensor_name(getSensorName(monitor.getSensor_id(),sensorList));
                monitorExport.setMonitor_name(monitor.getName());
                monitorExport.setMonitor_code(monitor.getDescription());
                monitorExportList.add(monitorExport);
            }

            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            String[] columns = {"区域","建筑物","楼层","报警主机","主机IP","主机备注","传感器类别","监测点名称","监测点回路号"};
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < monitorExportList.size() +1; i++){
                wqh.pojo.MonitorExport a = monitorExportList.get(i-1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(a.getArea());
                cell = nextRow.createCell(1);
                cell.setCellValue(a.getBuilding());
                cell = nextRow.createCell(2);
                cell.setCellValue(a.getFloor());
                cell = nextRow.createCell(3);
                cell.setCellValue(a.getDevice_name());
                cell = nextRow.createCell(4);
                cell.setCellValue(a.getDevice_ip());
                cell = nextRow.createCell(5);
                cell.setCellValue(a.getDevice_model());
                cell = nextRow.createCell(6);
                cell.setCellValue(a.getSensor_name());
                cell = nextRow.createCell(7);
                cell.setCellValue(a.getMonitor_name());
                cell = nextRow.createCell(8);
                cell.setCellValue(a.getMonitor_code());
            }
            String fileName = "消控联网可视化系统监测点信息.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();

            xkLog.addLog(systemLogService,"导出 " + fileName,xkLog.getFileConfig(),userName);

            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

    @RequestMapping(value = "/template",method = RequestMethod.GET)
    public Object template(HttpServletRequest request, HttpServletResponse response)
    {
        System.out.println("导出");

        try {
            String sessionID = request.getSession().getId();
            String userName = GlobalSession.getUserNameBySessionID(sessionID);
            if(userName == null) userName = "空用户";

            String columns[] = {"用户信息传输装置名称","用户信息传输装置装置IP","区域","建筑物","楼层","传感器类型","监测点名称","报警回路号"};
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
            HSSFSheet hssfSheet = hssfWorkbook.createSheet();
            hssfSheet.addMergedRegion(new CellRangeAddress(0,0,0,columns.length - 1));
            HSSFRow titleRow = hssfSheet.createRow(0);
            titleRow.setHeightInPoints(40);
            HSSFCellStyle cellStyleTitle = hssfWorkbook.createCellStyle();
            Font fontTitle = hssfWorkbook.createFont();
            fontTitle.setFontHeight((short)500);
            fontTitle.setFontName("楷体");
            fontTitle.setColor(IndexedColors.RED.getIndex());
            fontTitle.setBoldweight(Font.BOLDWEIGHT_BOLD);
            cellStyleTitle.setFont(fontTitle);
            cellStyleTitle.setBorderRight(CellStyle.BORDER_THIN);
            cellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
            HSSFCell titleCell = titleRow.createCell(0);
            titleCell.setCellValue("消控联网系统监测点导入模板");
            titleCell.setCellStyle(cellStyleTitle);
            HSSFCell titleRightCell = titleRow.createCell(columns.length - 1);
            titleRightCell.setCellStyle(cellStyleTitle);
            for(int i = 0; i < columns.length; i++){
                hssfSheet.setColumnWidth(i,38*150);
            }
            HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
            Font font = hssfWorkbook.createFont();
            font.setFontHeight((short)200);
            font.setColor(IndexedColors.BLACK.getIndex());
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            cellStyle.setFont(font);
            cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
            cellStyle.setBorderRight(CellStyle.BORDER_THIN);
            cellStyle.setBorderTop(CellStyle.BORDER_THIN);
            cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
            cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
            HSSFRow hssfRow = hssfSheet.createRow(1);
            for(int i = 0 ; i < columns.length; i++)
            {
                HSSFCell hssfCell = hssfRow.createCell(i);
                hssfCell.setCellValue(columns[i]);
                hssfCell.setCellStyle(cellStyle);
            }
            String fileName = "消控联网可视化监测点录入模板.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            hssfWorkbook.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();

            xkLog.addLog(systemLogService,"导出 " + fileName,xkLog.getFileConfig(),userName);

            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }


    public String getGeobuildingName(int geoID,List<GeoBuilding> geoBuildings){
        for(GeoBuilding geoBuilding : geoBuildings){
            if(geoBuilding.getId() == geoID){
                return geoBuilding.getName();
            }
        }
        return null;
    }

    public String getDeviceName(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return device.getName();
        }
        return null;
    }

    public String getDeviceIP(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return IPConver.int2Ip(device.getIp());
        }
        return null;
    }

    public String getDeviceModel(int deviceID,List<Device> devices){
        for(Device device : devices){
            if(device.getId() == deviceID) return device.getDescription();
        }
        return null;
    }

    public String getSensorName(int sensorID, List<Sensor> sensorList){
        for(Sensor sensor : sensorList){
            if(sensor.getId() == sensorID)
                return sensor.getName();
        }
        return null;
    }

}
